<template>
  <div>
    <!-- 添加或修改土建过程话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" :fullscreen="formActive == 2" width="800px" append-to-body @close="reset()">
      <el-steps :active="formActive" finish-status="success" simple class="steps-row">
        <el-step title="基础信息" />
        <el-step title="随机区域" />
        <el-step title="完成" />
      </el-steps>
      <el-form v-show="formActive === 1" ref="form" :inline="true" :model="form" :rules="rules" label-width="80px">
        <el-form-item
          label="项目"
          prop="projectId"
        >
          <el-select
            v-model="form.projectId"
            placeholder="请选择项目"
            filterable
            clearable
            style="width: 280px"
            @change="getBuildingList"
          >
            <el-option
              v-for="project in formProjectOptions"
              :key="project.fid"
              :label="project.cflastname"
              :value="project.fid"
            />
          </el-select>
          <!-- <treeselect
            v-model="form.projectId"
            :flat="true"
            style="width: 280px;"
            :options="deptProjectOptions"
            :normalizer="normalizer"
            @select="getBuildingList"
            no-options-text="暂无数据"
            placeholder="请选择项目"
          />-->
        </el-form-item>
        <el-form-item label="检查单位" prop="randomType">
          <el-radio-group v-model="form.randomType">
            <el-radio
              v-for="dict in randomOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="检查人员" prop="principalUserName">
          <el-input readonly v-model="form.principalUserName" auto-complete="off" style="width: 280px;" placeholder="请选择抽检人员">
            <el-button slot="append" icon="el-icon-user-solid" @click="selectPrincipal" />
          </el-input>
        </el-form-item>
        <el-form-item label="检查日期" prop="checkDate">
          <el-date-picker
            v-model="form.checkDate"
            type="date"
            style="width: 280px;"
            placeholder="选择日期"
          />
        </el-form-item>
        <div class="construction-dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button v-if="form.randomId" type="success" @click="formActive=2">下 一 步</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-form>
      <div v-show="formActive === 2" class="spot-check-area">
        <div class="random-builder">
          <div class="builder-first-row">
            <span class="builder-title">随机抽检生成器</span>
            <span class="operate-btn">
              <el-button class="operate" type="success" icon="el-icon-edit" size="mini" @click="generateRadom()" style="margin-right: 20px;" :loading="randomLoading">随机生成</el-button>
            </span>
          </div>
          <el-form ref="randomForm" :inline="true" :model="randomForm" :rules="randomRules" label-width="80px">
            <el-form-item label="模块" prop="scoreType">
              <el-select
                v-model="randomForm.scoreType"
                placeholder="请选择模块"
                filterable
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="module in moduleOptions"
                  :key="module.dictValue"
                  :label="module.dictLabel"
                  :value="module.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="随机类型" prop="randomMethod">
              <el-select
                v-model="randomForm.randomMethod"
                placeholder="随机类型"
                clearable
                style="width: 200px"
                @change="randomTypeChange"
              >
                <el-option
                  v-for="dict in randomAreaTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="楼栋范围" prop="buildIds">
              <el-select
                v-model="randomForm.buildIds"
                placeholder="请选择楼栋"
                collapse-tags
                :multiple="randomForm.randomMethod == 'build'"
                filterable
                clearable
                @focus="buildFoucus"
                style="width: 200px"
              >
                <el-option
                  v-for="build in buildings"
                  :key="build.id"
                  :label="build.name"
                  :value="build.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="randomForm.randomMethod == 'floor' || randomForm.randomMethod == 'room'" label="楼层范围" prop="startRange">
              <el-input
                v-model.number="randomForm.startRange"
                placeholder="开始楼层"
                style="width: 90px"
              />
              <i class="el-icon-minus relation-accord" />
              <el-input
                v-model.number="randomForm.endRange"
                placeholder="结束楼层"
                style="width: 90px"
                :disabled="randomForm.randomMethod == 'build' || randomForm.randomMethod == 'under'"
              />
            </el-form-item>
            <el-form-item label="抽取数量" prop="randomCount">
              <el-input-number
                v-model="randomForm.randomCount"
                placeholder="请输入数量"
                controls-position="right"
                style="width: 200px"
                :min="1"
              />
            </el-form-item>
            <el-form-item v-if="randomForm.randomMethod == 'under'" label="地下室" prop="underIds">
              <el-select
                v-model="randomForm.underIds"
                placeholder="请选择区域"
                multiple
                collapse-tags
                filterable
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="build in buildings"
                  :key="build.id"
                  :label="build.name"
                  :value="build.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <el-divider><span class="random-result-desc">随机生成结果</span></el-divider>
          <div class="random-result" v-loading="randomLoading">
            <div v-for="(random, dIndex) in randomList" :key="'random' + dIndex" class="custom-card">
              <span class="random-type">{{ random.randomMethod | randomMethod }}</span>
              <el-card style="margin: 10px 0 0 16px;">
                <i v-if="!random.saved" class="el-icon-error card-close" @click="removeRandom(dIndex)" />
                <div class="module">
                  <el-tag size="small">{{ random.scoreType | scoreType(moduleOptions) }}</el-tag>
                </div>
                <div v-for="(result, rIndex) in random.results" :key="'result'+rIndex" class="area-name">
                  {{ result.name }}
                </div>
              </el-card>
            </div>
          </div>
        </div>
        <div class="construction-dialog-footer">
          <el-button type="primary" @click="submitRandomForm">确 定</el-button>
          <el-button type="success" @click="formActive=1">上 一 步</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 选择人员 -->
    <select-user-dialog
      :show.sync="showSelectUserVisible"
      :selected="selectedUser"
      :multi="false"
      @select="selectUserHandle"
    />
  </div>
</template>

<script>
import SelectUserDialog from '../../../components/SelectUserDialog.vue'
import { buildingList, getAuthCurProject } from '@/api/common'
import {
  cqRdcScoreAdd,
  cqRdcScoreEdit,
  cqRdcAreaList,
  generateRadom,
  saveRandomResult
} from '@/api/projectInspection/courseCheck'
export default {
  name: 'AddUpdate',
  components: { SelectUserDialog },
  filters: {
    randomMethod(val) {
      let result = ''
      switch (val) {
        case 'build':
          result = '楼'
          break
        case 'floor':
          result = '层'
          break
        case 'room':
          result = '房'
          break
        case 'under':
          result = '地'
          break
        default:
          result = val
          break
      }
      return result
    },
    scoreType(val, list) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].dictValue === val) {
          return list[i].dictLabel
        }
      }
    }
  },
  props: {
    specialTypeFid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 表单步骤
      formActive: 1,
      open: false,
      // 弹出层标题
      title: '',
      // 检查单位 数据字典
      randomOptions: [],
      // 表单 楼栋选择列表
      buildings: [],
      // 随机生成器 表单
      randomForm: {
        buildIds: [],
        scoreType: [],
        underIds: [],
        startRange: null,
        endRange: null,
        randomMethod: '',
        randomCount: 1
      },
      // 生成随机结果类型
      randomAreaTypeOptions: [],
      formProjectOptions: [],
      // 随机生成列表
      randomList: [],
      // randomList: [{"buildIds":"YZYislVuQnyMIqoai6L4MRWcbo8=","scoreType":"fsl","underIds":[],"startRange":3,"endRange":9,"randomMethod":"floor","randomCount":3,"results":[{"id":"4","name":"爱琴海一期-4层"},{"id":"6","name":"爱琴海一期-6层"},{"id":"8","name":"爱琴海一期-8层"}]},{"buildIds":"YZYislVuQnyMIqoai6L4MRWcbo8=","scoreType":"fsl","underIds":[],"startRange":3,"endRange":9,"randomMethod":"floor","randomCount":3,"results":[{"id":"4","name":"爱琴海一期-4层"},{"id":"8","name":"爱琴海一期-8层"},{"id":"9","name":"爱琴海一期-9层"}]},{"buildIds":"YZYislVuQnyMIqoai6L4MRWcbo8=","scoreType":"fsl","underIds":[],"startRange":3,"endRange":9,"randomMethod":"floor","randomCount":3,"results":[{"id":"4","name":"爱琴海一期-4层"},{"id":"5","name":"爱琴海一期-5层"},{"id":"9","name":"爱琴海一期-9层"}]},{"buildIds":"YZYislVuQnyMIqoai6L4MRWcbo8=","scoreType":"fsl","underIds":[],"startRange":3,"endRange":9,"randomMethod":"floor","randomCount":3,"results":[{"id":"4","name":"爱琴海一期-4层"},{"id":"6","name":"爱琴海一期-6层"},{"id":"3","name":"爱琴海一期-3层"}]}],
      randomLoading: false,
      randomRules: {
        randomMethod: [
          { required: true, message: '请选择随机类型', trigger: 'change' }
        ],
        randomCount: [
          { required: true, message: '请填写抽取数量', trigger: 'blur' }
        ],
        buildIds: [
          { required: true, message: '请选择楼栋', trigger: 'change' }
        ],
        scoreType: [
          { required: true, message: '请选择模块', trigger: 'change' }
        ]
      },
      // 模块选项
      moduleOptions: [
        {dictValue: 'fsl', dictLabel: '防渗漏'},
        {dictValue: 'zl-scsl', dictLabel: '质量-实测实量'},
        {dictValue: 'zl-gg', dictLabel: '质量-观感'},
        {dictValue: 'zl-kgkl', dictLabel: '质量-空鼓开裂'},
        {dictValue: 'zl-cpbh', dictLabel: '质量-成品保护'},
        {dictValue: 'jgaq', dictLabel: '结构安全'},
        {dictValue: 'gldz', dictLabel: '管理动作'}
      ],
      // 表单参数
      form: {
        projectId: undefined,
        randomType: undefined,
        principalId: undefined,
        principalUserName: undefined,
        checkDate: undefined
      },
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        randomType: [
          { required: true, message: '请选择检查单位', trigger: 'change' }
        ],
        checkDate: [
          { required: true, message: '请选择检查时间', trigger: 'change' }
        ],
        principalUserName: [
          { required: true, message: '请选择检查人员', trigger: 'change' }
        ]
      },
      specialTypeName: '',
      // 选择用户窗口
      showSelectUserVisible: false,
      selectedUser: []
    }
  },
  created() { // 初始化
    this.getDicts('cq_random_type').then(response => {
      this.randomOptions = response.data
    })
    this.getDicts('cq_random_area_type').then(response => {
      this.randomAreaTypeOptions = response.data
    })
    this.getDeptTree()
  },
  mounted() {
    const path = this.$route.path
    this.specialTypeName = path.includes('ConstructionCourse') ? '土建' : '精装'
  },
  methods: {
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = this.specialTypeName + '过程'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form.projectId = row.projectId
      this.form.randomType = row.randomType
      this.form.principalUserName = row.principalUserName
      this.form.principalId = row.principalId
      this.form.checkDate = row.checkDate
      this.form.randomId = row.randomId
      this.open = true
      this.title = this.specialTypeName + '过程'
      this.getBuildingList(row.projectId)
      this.getRandomList()
    },
    // 根据抽检记录查询抽检区域
    getRandomList() {
      const params = {
        randomId: this.form.randomId
      }
      cqRdcAreaList(params).then((response) => {
        if (response.code === 200) {
          const list = response.data
          // 针对键 randomRecordId 进行归类的容器
          const baseContainer = {}
          list.forEach(item => {
            if (item.randomRecordId) {
              baseContainer[item.randomRecordId] = baseContainer[item.randomRecordId] || []
              baseContainer[item.randomRecordId].push({...item, name: item.areaName })
            }
          })
          const randomList = []
          for (const key in baseContainer) {
            if (baseContainer[key].length > 0) {
              randomList.push({
                randomRecordId: key,
                saved: true,
                scoreType: baseContainer[key][0]['belongType'],
                randomMethod: baseContainer[key][0]['randomType'],
                results: baseContainer[key]
              })
            }
          }
          this.randomList = randomList
        }
      })
    },
    // 抽取随机类型改变
    randomTypeChange(val) {
      if (this.randomForm.randomMethod === 'build' && typeof this.randomForm.buildIds === 'string') {
        this.randomForm.buildIds = []
      } else if (this.randomForm.randomMethod !== 'build' && typeof this.randomForm.buildIds === 'object') {
        this.randomForm.buildIds = ''
      }
    },
    // 选择楼栋获取焦点提示
    buildFoucus() {
      if (!this.form.projectId) {
        this.$message.error('请先选择项目。')
        this.$refs.form.validateField('projectId')
      }
    },
    // 根据项目ID获取楼栋列表
    getBuildingList(projectId) {
      for (let i = 0; i < this.formProjectOptions.length; i++) {
        if (projectId === this.formProjectOptions[i].fid) {
          this.currentFormProject = this.formProjectOptions[i]
        }
      }
      buildingList({ projectId: projectId }).then((response) => {
        if (response.code === 200) {
          this.buildings = response.data
        }
      })
    },
    /**
     * 查询部门与项目下拉树结构
     */
    getDeptTree() {
      getAuthCurProject().then((response) => {
        this.formProjectOptions = response.data
      })
    },
    // 人员选择结束回调
    selectUserHandle(selection) {
      console.log(selection)
      this.form.principalUserName = selection[0].label
      this.form.principalId = selection[0].value
    },
    // 打开选择项目总
    selectPrincipal() {
      const selectedUser = []
      const principalIds = this.form.principalIds ? this.form.principalIds.split(',') : []
      const principalNames = this.form.principalNames ? this.form.principalNames.split(',') : []
      if (principalNames.length > 0 && principalIds.length > 0) {
        principalIds.forEach((item, index) => {
          selectedUser.push({ value: item, label: principalNames[index] })
        })
      }
      this.selectedUser = selectedUser
      this.showSelectUserVisible = true
    },
    // 取消按钮
    cancel() {
      this.open = false
      setTimeout(() => {
        this.reset()
      }, 500)
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: undefined,
        randomType: undefined,
        principalId: undefined,
        principalUserName: undefined,
        checkDate: undefined
      }
      this.randomForm = {
        buildIds: null,
        scoreType: [],
        underIds: [],
        startRange: null,
        endRange: null,
        randomMethod: '',
        randomCount: 1
      }
      this.formActive = 1
      this.randomList = []
      this.resetForm('form')
      this.resetForm('randomForm')
    },
    /** 保存抽检基础信息 */
    submitForm() {
      this.form.specialTypeId = this.specialTypeFid
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.randomId !== undefined) {
            cqRdcScoreEdit(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.formActive = 2
                // this.open = false
                // this.$nextTick(() => {
                //   delete this.form.randomId
                // })
                // this.getList()
              }
            })
          } else {
            cqRdcScoreAdd(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.formActive = 2
                this.form.randomId = response.data.randomId
                // this.open = false
                // this.getList()
              }
            })
          }
        }
      })
    },
    /** 保存抽检 随机区域 */
    submitRandomForm() {
      this.$refs['randomForm'].validate(valid => {
        if (valid) {
          let cqRandomParamVOS = JSON.parse(JSON.stringify(this.randomList))
          cqRandomParamVOS = cqRandomParamVOS.filter(item => !item.saved)
          for (let i = 0; i < cqRandomParamVOS.length; i++) {
            if (typeof cqRandomParamVOS[i].buildIds === 'string') {
              cqRandomParamVOS[i].buildIds = [cqRandomParamVOS[i].buildIds]
            }
            cqRandomParamVOS[i].results = cqRandomParamVOS[i].results.map(result => result.id)
          }
          const params = {
            cqRandomParamVOS: cqRandomParamVOS,
            projectId: this.form.projectId,
            randomId: this.form.randomId
          }
          saveRandomResult(params).then(response => {
            if (response.code === 200) {
              this.msgSuccess('新增成功')
              this.formActive = 3
              this.open = false
              this.$nextTick(() => {
                delete this.form.randomId
              })
              // this.getList()
              this.reset()
              this.$emit('close')
            }
          })
        }
      })
    },
    // 生成随机抽检区域
    generateRadom() {
      this.$refs['randomForm'].validate(valid => {
        if (valid) {
          if (this.randomForm.startRange > 0 && this.randomForm.endRange > 0) {
            if (this.randomForm.startRange > this.randomForm.endRange) {
              this.$message.error('开始楼层不能大于结束楼层。')
              return
            }
          }
          const params = {
            ...this.randomForm
          }
          if (typeof params.buildIds === 'string') {
            params.buildIds = [params.buildIds]
          }
          params.randomId = this.form.randomId
          this.randomLoading = true
          generateRadom(params).then((response) => {
            if (response.code === 200) {
              // this.buildings = response.data
              const resData = response.data.info || response.data
              const results = []
              if (this.randomForm.randomMethod === 'floor') {
                let currentBuilding = {}
                for (let i = 0; i < this.buildings.length; i++) {
                  if (this.buildings[i].id === this.randomForm.buildIds) {
                    currentBuilding = this.buildings[i]
                  }
                }
                for (let i = 0; i < resData.floorList.length; i++) {
                  results.push({ id: resData.floorList[i], name: `${this.currentFormProject.cflastname} - ${currentBuilding.name} - ${resData.floorList[i]}层` })
                }
              } else {
                for (const key in resData) {
                  results.push({ id: key, name: resData[key] })
                }
              }
              this.randomList.push({
                ...this.randomForm,
                randomRecordId: response.data.randomRecordId,
                results
              })
            }
          }).finally(() => {
            setTimeout(() => {
              this.randomLoading = false
            }, 1000)
          })
        }
      })
    },
    // 删除随机生成数据
    removeRandom(index) {
      this.randomList.splice(index, 1)
    }
  }
}
</script>

<style scoped lang='scss'>
  $borderColor: #E4E7ED;
  .steps-row {
    margin-bottom: 20px;
  }
  .spot-check-area {
    padding: 0 30px 0 20px;
    .random-builder {
      padding: 0px 20px 10px;
      border: 1px solid $borderColor;
      border-radius: 5px;
      .builder-first-row {
        background-color: #5dd0ff;
        border-radius: 4px 4px 0 0;
        height: 40px;
        line-height: 40px;
        padding-left: 20px;
        margin: 0 -20px 20px -20px;
        position: relative;
        display: flex;
        justify-content: space-between;
        .builder-title {
          font-weight: bold;
          font-size: 16px;
          color: #ffffff;
        }
        .operate-btn {
        }
      }
      .builder-operate {
        position: relative;
        height: 10px;
        .operate {
          position: absolute;
          right: 20px;
          top: -10px;
        }
      }
      .relation-accord {
        width: 20px;
        text-align: center;
        color: $borderColor;
      }
      .random-result-desc {
        color: #67c23a;
        font-style: italic;
      }
      .random-result {
        display: flex;
        flex-wrap: wrap;
        height: 420px;
        overflow-y: auto;
        .custom-card {
          width: 220px;
          position: relative;
          color: #606266;
          &:hover {
            .card-close {
              display: inline-block;
            }
          }
          .card-close {
            display: none;
            position: absolute;
            top: 16px;
            right: 6px;
            font-size: 18px;
            cursor: pointer;
            color: #b3bcc6;
            &:hover {
              color: #409EFF;
            }
          }
          .random-type {
            position: absolute;
            top: 2px;
            left: 8px;
            width: 20px;
            height: 20px;
            line-height: 20px;
            border-radius: 50%;
            background-color: #67c23a;
            color: #ffffff;
            text-align: center;
            font-size: 12px;
          }
          .module {
            text-align: center;
            margin-bottom: 10px;
          }
          .area-name {
            margin-top: 6px;
            color: #606266;
            font-size: 12px;
            text-align: center;
          }
        }
      }
    }
  }
  .construction-dialog-footer {
    padding: 20px 30px 0 20px;
    text-align: right;
  }
</style>
